package com.rmondjone.base


import android.content.Context
import android.content.Intent
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.view.View
import android.webkit.*
import android.widget.ProgressBar
import com.rmondjone.androidcamerademo.R
import com.rmondjone.camera.BaseActivity
import com.rmondjone.utils.StatusBarUtil
import com.rmondjone.utils.setClickListener
import kotlinx.android.synthetic.main.activity_web.*

/**
 * copyright：
 * @author：anthui creation date： .
 * @since: 1.0.0
 * @describe:
 */
class WeViewActivity : BaseActivity() {


    companion object {

        fun setWebActivity(context: Context, url: String) {
            val intent = Intent(context, WeViewActivity::class.java)
            intent.putExtra("url", url)
            context.startActivity(intent)
        }
    }


    lateinit var mWebView: WebView
    lateinit var mProgression: ProgressBar
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web)

        mWebView = findViewById<WebView>(R.id.web_viewl)
        mProgression = findViewById(R.id.progressBar)

        StatusBarUtil.setStatusBarDarkFontMode(this)
        initWebView()

        iv_back.setClickListener { finish() }
        val stringExtra = intent.getStringExtra("url")
        loadWeb(stringExtra)
//        loadWeb("https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&tn=baidu&wd=isRestricted&oq=glide%25E5%258F%25AA%25E4%25B8%258B%25E8%25BD%25BD%25E5%259B%25BE%25E7%2589%2587&rsv_pq=a686b9850000b557&rsv_t=53542H8kZwS0wa%2FUkMG8xV7I7WS3BsN1qpMToL6ijdHpAiC4pnSwtkVseB4&rqlang=cn&rsv_enter=0&rsv_dl=tb&rsv_n=2&rsv_sug3=1&rsv_btype=t&inputT=915&rsv_sug4=915")
    }


    /**
     * copyright：
     * @author：anthui creation date： 2020/9/1.
     * @since: 1.0.0
     * @describe: 加载链接
     */

    private fun loadWeb(url: String) {

        mWebView.loadUrl(url)

    }

    private fun initWebView() {
        val setting: WebSettings = mWebView.settings
        // 支持缩放
        // 支持缩放
        setting.setSupportZoom(false)
        // 设置支持缩放 + -
        // 设置支持缩放 + -
        setting.builtInZoomControls = true
        // 关闭 webView 中缓存
        /**/
        /*webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);*/
        // 关闭 webView 中缓存
        /**/
        setting.useWideViewPort =
                true
        setting.loadWithOverviewMode = true
        // 设置WebView属性，能够执行Javascript脚本
        // 设置WebView属性，能够执行Javascript脚本
        setting.javaScriptEnabled = true
        setting.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        setting.savePassword = false
        setting.domStorageEnabled = true
        setting.allowFileAccess = true
        setting.defaultTextEncodingName = "utf-8"
        // 设置UserAgent
        // 设置UserAgent
        setting.blockNetworkImage = false // 解决图片不显示

        setting.displayZoomControls = false

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setting.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }


        mWebView.webViewClient = object : WebViewClient() {
            override fun onReceivedSslError(
                    view: WebView?,
                    handler: SslErrorHandler, error: SslError?
            ) {
                handler.proceed() // 接受证书
            }

            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {

                if (url.isNullOrEmpty()) {
                    return false
                }
                try {
                    // 处理自定义scheme协议
                    if (!url.startsWith("http") && !url.startsWith("https")) {
                        return try {
                            val intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME)
                            intent.flags =
                                    Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP
                            intent.addCategory("android.intent.category.BROWSABLE")
                            intent.component = null
                            if (null != intent) {
                                startActivity(intent)
                            }
                            true
                        } catch (e: Exception) {
                            // 没有安装的情况
                            e.printStackTrace()
                            //                            ToastUitl.showShort("尚未安装此应用！");
                            true
                        }
                    }

                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }
                return super.shouldOverrideUrlLoading(view, url)

            }


        }

        mWebView.webChromeClient = object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView?, title: String?) {
                super.onReceivedTitle(view, title)
                if (title.isNullOrEmpty()) {
                    return
                }
                tv_title.text = title
            }

            override fun onProgressChanged(
                    view: WebView?,
                    newProgress: Int
            ) {
                super.onProgressChanged(view, newProgress)
                if (newProgress == 100) {
                    mProgression.visibility = View.GONE
                } else {
                    mProgression.visibility = View.VISIBLE
                    mProgression.progress = newProgress //设置加载进度
                }
            }

        }
        mWebView.setDownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->

//            LogUtil.e(
//                    "tag",
//                    "msg--------- " + url + "  userAgent== " + userAgent + "contentDisposition =" + contentDisposition
//            )
//            if (url.isNullOrEmpty()) {
//                return@setDownloadListener
//            }
//            val intent = Intent(Intent.ACTION_VIEW)
//            intent.addCategory(Intent.CATEGORY_BROWSABLE)
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//            intent.setDataAndType(Uri.parse(url), "text/html")
//            startActivity(intent)
//            finish()
        }
    }

    override fun onDestroy() {

        mWebView.stopLoading()
        // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
        // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
        mWebView.getSettings().setJavaScriptEnabled(false)
        mWebView.clearHistory()
//        mWebView.clearView()
        mWebView.removeAllViews()
        mWebView.destroy()
        super.onDestroy()

    }

}